import * as cc from 'cc';

const { ccclass, property, executionOrder } = cc._decorator;

class KeyInterval {
    constructor(keyCode: number, interval: number) {
        this.keyCode = keyCode;
        this.interval = interval;
    }
    public keyCode: number;
    public interval: number;
}

@ccclass('KeyInput')
@executionOrder(1)
export class KeyInput extends cc.Component {
    interval: number = 0;
    keyBuffer: KeyInterval[] = [];
    // 用于记录当前帧的按键状态
    private current: Map<number, boolean> = new Map<number, boolean>();
    // 用于记录上一帧的按键状态
    private last: Map<number, boolean> = new Map<number, boolean>();

    onLoad() {}

    start() {
        cc.input.on(cc.Input.EventType.KEY_DOWN, this.onKeyDown, this);
        cc.input.on(cc.Input.EventType.KEY_UP, this.onKeyUp, this);
        //游戏进入后台时触发
        cc.game.on(cc.Game.EVENT_HIDE, this._resetKey, this);
    }

    lateUpdate(dt: number) {
        this.interval++;
        // 记录上一帧的 input 状态
        this.last = new Map(this.current);
    }

    private onKeyDown(key: cc.EventKeyboard) {
        this.current.set(key.keyCode, true);

        // this.interval = 0;
        // this.keyBuffer.push(new KeyInterval(key.keyCode, this.interval));
    }

    private onKeyUp(key: cc.EventKeyboard) {
        this.current.set(key.keyCode, false);
    }

    /**
     * 获取被按下的键
     * @param key
     * @returns
     */
    public getKey(key: number) {
        return this.current.get(key);
    }

    debug(key: number) {
        console.log(key, this.current, this.last);
    }
    /**
     * 检测本帧某个按键是否刚被按下
     * @param key
     */
    public getKeyDown(key: number) {
        const last = this.last.get(key) || false;
        const now = this.current.get(key) || false;
        return !last && now;
    }

    /**
     * 检测本帧某个按键是否刚被松开
     * @param key
     */
    public getKeyUp(key: number) {
        const last = this.last.get(key) || false;
        const now = this.current.get(key) || false;
        console.log('last', last, 'now', now);
        return last && !now;
    }

    private _resetKey() {
        this.current.clear();
        this.last.clear();
    }
}
